/**
 * Sample TypeScript main entry point for testing entry point discovery.
 */

import express from 'express';
import { DataProcessor } from './core/processor';
import { setupLogging, validateInput } from './utils/helpers';
import { APIClient } from './api/client';

interface AppConfig {
  port: number;
  verbose: boolean;
  apiKey?: string;
}

function parseArguments(): AppConfig {
  const config: AppConfig = {
    port: 3000,
    verbose: false
  };

  const args = process.argv.slice(2);
  
  for (let i = 0; i < args.length; i++) {
    switch (args[i]) {
      case '--port':
      case '-p':
        config.port = parseInt(args[++i], 10);
        break;
      case '--verbose':
      case '-v':
        config.verbose = true;
        break;
      case '--api-key':
        config.apiKey = args[++i];
        break;
      case '--help':
      case '-h':
        console.log('Usage: npm start [options]');
        console.log('Options:');
        console.log('  -p, --port <port>     Server port (default: 3000)');
        console.log('  -v, --verbose         Enable verbose logging');
        console.log('  --api-key <key>       API key for external services');
        console.log('  -h, --help            Show this help message');
        process.exit(0);
        break;
    }
  }

  return config;
}

async function processFile(filePath: string): Promise<boolean> {
  try {
    const processor = new DataProcessor();
    
    if (!validateInput(filePath)) {
      console.error(`Invalid input file: ${filePath}`);
      return false;
    }

    const result = await processor.processFile(filePath);
    console.log('Processing completed:', result);
    
    return true;
  } catch (error) {
    console.error('Error processing file:', error);
    return false;
  }
}

function setupServer(config: AppConfig): express.Application {
  const app = express();
  
  app.use(express.json());
  
  // Health check endpoint
  app.get('/health', (req, res) => {
    res.json({ status: 'healthy', timestamp: new Date().toISOString() });
  });
  
  // Process file endpoint
  app.post('/process', async (req, res) => {
    const { filePath } = req.body;
    
    if (!filePath) {
      return res.status(400).json({ error: 'filePath is required' });
    }
    
    const success = await processFile(filePath);
    
    if (success) {
      res.json({ success: true, message: 'File processed successfully' });
    } else {
      res.status(500).json({ error: 'Failed to process file' });
    }
  });
  
  return app;
}

async function main(): Promise<number> {
  try {
    const config = parseArguments();
    
    // Setup logging
    setupLogging(config.verbose);
    
    // Setup API client if key provided
    if (config.apiKey) {
      const apiClient = new APIClient('https://api.example.com', config.apiKey);
      // Store globally or pass to components that need it
    }
    
    // Setup and start server
    const app = setupServer(config);
    
    app.listen(config.port, () => {
      console.log(`Server running on port ${config.port}`);
    });
    
    return 0;
  } catch (error) {
    console.error('Application error:', error);
    return 1;
  }
}

// Entry point
if (require.main === module) {
  main().then(exitCode => {
    process.exit(exitCode);
  });
}

export { main, processFile, setupServer };